app.controller("itemController",function ($scope,$http) {
   $scope.num=1;
   //数量的加减
   $scope.addNum=function(x){
       $scope.num=$scope.num+x;
       if($scope.num<1){
           $scope.num=1;
       }
    }
    $scope.specificationItems={};//记录用户选择的规格
    //用户选择规格
    $scope.selectSpecification=function(name,value){
        $scope.specificationItems[name]=value;
        //读取sku
        searchSku();
    }
    //判断某规格选项是否被用户选中
    $scope.isSelected=function(name,value){
        if($scope.specificationItems[name]==value){
            return true;
        }else{
            return false;
        }
    }

    $scope.sku;
    //加载默认SKU
    $scope.loadSku=function(){
        $scope.sku=skuList[0];
        $scope.specificationItems= JSON.parse(JSON.stringify($scope.sku.spec)) ;
    }
    // 判断连个集合是否匹配
    matchObject=function(map1,map2){
        //循环 map 集合
        for(var k in map1){
            if(map1[k]!=map2[k]){
                return false;
            }
        }
        //把集合反过来，避免两个集合中元素不一致出现漏洞
        for(var k in map2){
            if(map2[k]!=map1[k]){
                return false;
            }
        }
        return true;
    }
    //查询sku ，并与选中的规格作比较得到选中的
	searchSku=function(){
		for(var i=0;i<skuList.length;i++ ){
			if( matchObject(skuList[i].spec ,$scope.specificationItems ) ){
				$scope.sku=skuList[i];
				return ;
			}			
        }	
        //如果没有匹配的	
        $scope.sku={id:0,title:'--------',price:0};	
        alert("暂无此规格商品");
    }
    //添加商品到购物车
    $scope.addToCart=function(){
        $http.get('http://localhost:8089/cartController/addGoodsToCartList.do?itemId='
            + $scope.sku.id +'&num='+$scope.num,{'withCredentials':true}).success(
            function(response){
                if(200==response.code){
                    location.href='http://localhost:8089/cart.html';//跳转到购物车页面
                }else{
                    alert(response.message);
                }
            }
        );

    }

    $scope.search=function(){
        location.href="http://localhost:8084/search.html#?keywords="+$scope.keywords;
    }
});
